﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using AuthoritExtensibility;
using API = Authorit.API;
using Dto = Authorit.API.Dto;

namespace MiniExporter {

  class Exporter {

    static void Main(string[] args) {

      API.Configuration.LibraryConfigurationList config = null;
      API.Services.Authentication authentication = null;
      API.ApplicationContext context = null;
      API.Services.Topic topicservice = null;
      API.Services.ObjectCommon common = null;
      DateTime now = DateTime.Now;

      const string server = @""; // Server name
      const string alias = "Library";
      string database = ""; // Database name, like 'production'
      string user = "", pass = ""; // Username and password
      string output;

      config = new API.Configuration.LibraryConfigurationList(new API.Configuration.SqlServerLibraryConfiguration(alias, server, database));
      //config = new API.Configuration.LibraryConfigurationList(new API.Configuration.JetLibraryConfiguration(alias, server));
      context = new API.ApplicationContext(config);
      authentication = context.GetServiceInstance<API.Services.Authentication>();
      topicservice = context.GetServiceInstance<API.Services.Topic>();
      common = context.GetServiceInstance<API.Services.ObjectCommon>();

      Dto.LoginResponse response = new Dto.LoginResponse();
      response = authentication.Login(alias, user, pass);

      Console.Write("Enter object ID: ");
      string objectid = Console.ReadLine();
      objectid.Trim();
      if (common.CheckExists(int.Parse(objectid))) {
        output = topicservice.GetTopicTextXml(int.Parse(objectid));
        Console.WriteLine("Here is the document:\n\n" + output + "\n");
        XmlReader reader = XmlReader.Create(new StringReader(output));
        Console.WriteLine("Here is a node analysis, line by line:\n");
        while (reader.Read()) {
          switch(reader.NodeType) {
           case XmlNodeType.Element:
              Console.WriteLine("Name: " + reader.Name);
              break;
           case XmlNodeType.Text:
              Console.WriteLine("Content: " + reader.Value);
              break;
            default:
              break;
          }
        }
      }
      Console.Write("\nPress Enter to exit.");
      Console.Read();

      authentication.Logout();

    }
  }
}
